import axios from 'axios'


// 防抖函数
export const debounce = (fn, delay) => {
  let timer = null
  return (...args) => {
    if (timer) clearTimeout(timer)
    timer = setTimeout(() => {
      fn.apply(this, args)
    }, delay)
  }
} 

/**
 * 处理医院对象的图片 URL
 * @param {Object} hospital - 医院对象
 * @param {string} token - 认证 token
 * @returns {Promise<Object>} - 返回处理后的医院对象
 */
export const processHospitalImage = async (hospital, token) => {
  try {
    // 如果图片 URL 为空，直接返回原始数据
    if (!hospital.image) {
      return hospital;
    }

    // 获取图片 blob 数据
    const response = await axios.get(hospital.image, {
      headers: {
        Authorization: `Bearer ${token}`,
      },
      responseType: 'blob',
    });

    // 创建 Blob URL
    const blob = new Blob([response.data], { type: response.headers['content-type'] });
    return {
      ...hospital,
      image: URL.createObjectURL(blob),
    };
  } catch (error) {
    console.error('处理医院图片失败：', error);
    return hospital; // 如果处理失败，返回原始数据
  }
};

//处理businessContent字段函数，将其解构出来添加到原数据中
export const parseBusinessContent = (obj) => {
  // 如果 businessContent 不存在，直接返回原始数据
  if (obj.businessContent) {
    console.log('没有解构')
    return obj;
  }
  console.log('开始解构')
  const { businessContent } = obj.value;
  if (businessContent) {
    // 使用正则表达式匹配键值对
    const regex = /(\w+):([^,]+)/g;
    let match;
    while ((match = regex.exec(businessContent))!== null) {
      const key = match[1];
      const value = match[2];
      obj.value[key] = value;
    }
    // 删除原始的 businessContent 字段
    delete obj.value.businessContent;
  }
  return obj;
};